<script setup lang="ts">
import { ref, reactive, computed, onMounted, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useResumeStore } from '../stores/resumeStore';
import { message, Modal } from 'ant-design-vue';
import type { Resume, Education, WorkExperience, Project, Skill, Certificate } from '../types';
import { v4 as uuidv4 } from 'uuid';

const route = useRoute();
const router = useRouter();
const resumeStore = useResumeStore();

const resumeId = computed(() => route.params.id as string);
const loading = ref(false);
const saving = ref(false);
const activeTab = ref('basic');
const resume = reactive<Partial<Resume>>({
  basicInfo: {
    id: '',
    name: '',
    title: '',
    contact: {
      email: '',
      phone: '',
      address: '',
      website: '',
      github: '',
      linkedin: ''
    },
    objective: ''
  },
  education: [],
  workExperience: [],
  projects: [],
  skills: [],
  certificates: [],
  name: ''
});

// 加载简历数据
onMounted(async () => {
  if (resumeId.value) {
    try {
      loading.value = true;
      const data = await resumeStore.fetchResume(resumeId.value);
      if (data) {
        Object.assign(resume, data);
      } else {
        message.error('找不到该简历');
        router.push('/resume/list');
      }
    } catch (error) {
      console.error('加载简历失败:', error);
      message.error('加载简历失败');
    } finally {
      loading.value = false;
    }
  }
});

// 保存简历
const saveResume = async () => {
  try {
    saving.value = true;
    if (resumeId.value) {
      await resumeStore.updateResume(resume as Resume);
    } else {
      const newResume = await resumeStore.createResume(resume);
      router.replace(`/resume/edit/${newResume.id}`);
    }
    message.success('保存成功');
  } catch (error) {
    console.error('保存简历失败:', error);
    message.error('保存简历失败');
  } finally {
    saving.value = false;
  }
};

// 预览简历
const previewResume = () => {
  if (resumeId.value) {
    router.push(`/resume/preview/${resumeId.value}`);
  } else {
    message.warning('请先保存简历');
  }
};

// 添加教育经历
const addEducation = () => {
  const newEducation: Education = {
    id: uuidv4(),
    institution: '',
    degree: '',
    major: '',
    startDate: '',
    endDate: '',
    gpa: '',
    description: ''
  };
  resume.education?.push(newEducation);
};

// 删除教育经历
const removeEducation = (id: string) => {
  if (resume.education) {
    resume.education = resume.education.filter(item => item.id !== id);
  }
};

// 添加工作经历
const addWorkExperience = () => {
  const newWorkExperience: WorkExperience = {
    id: uuidv4(),
    company: '',
    position: '',
    startDate: '',
    endDate: '',
    description: '',
    achievements: []
  };
  resume.workExperience?.push(newWorkExperience);
};

// 删除工作经历
const removeWorkExperience = (id: string) => {
  if (resume.workExperience) {
    resume.workExperience = resume.workExperience.filter(item => item.id !== id);
  }
};

// 添加项目经历
const addProject = () => {
  const newProject: Project = {
    id: uuidv4(),
    name: '',
    role: '',
    startDate: '',
    endDate: '',
    description: '',
    technologies: [],
    link: ''
  };
  resume.projects?.push(newProject);
};

// 删除项目经历
const removeProject = (id: string) => {
  if (resume.projects) {
    resume.projects = resume.projects.filter(item => item.id !== id);
  }
};

// 添加技能
const addSkill = () => {
  const newSkill: Skill = {
    id: uuidv4(),
    name: '',
    level: 3,
    category: ''
  };
  resume.skills?.push(newSkill);
};

// 删除技能
const removeSkill = (id: string) => {
  if (resume.skills) {
    resume.skills = resume.skills.filter(item => item.id !== id);
  }
};

// 添加证书
const addCertificate = () => {
  const newCertificate: Certificate = {
    id: uuidv4(),
    name: '',
    issuer: '',
    date: '',
    description: ''
  };
  resume.certificates?.push(newCertificate);
};

// 删除证书
const removeCertificate = (id: string) => {
  if (resume.certificates) {
    resume.certificates = resume.certificates.filter(item => item.id !== id);
  }
};

// 添加成就
const addAchievement = (workExperience: WorkExperience) => {
  workExperience.achievements.push('');
};

// 删除成就
const removeAchievement = (workExperience: WorkExperience, index: number) => {
  workExperience.achievements.splice(index, 1);
};

// 添加技术栈
const addTechnology = (project: Project) => {
  project.technologies.push('');
};

// 删除技术栈
const removeTechnology = (project: Project, index: number) => {
  project.technologies.splice(index, 1);
};

// 切换模板
const changeTemplate = (templateId: string) => {
  resume.templateId = templateId;
  saveResume();
};
</script>

<template>
  <div class="resume-edit-container">
    <a-spin :spinning="loading">
      <!-- 顶部操作栏 -->
      <div class="bg-white dark:bg-gray-800 rounded-lg shadow p-4 mb-6 flex justify-between items-center">
        <div>
          <a-input 
            v-model:value="resume.name" 
            placeholder="简历标题" 
            class="text-xl font-bold w-64"
          />
        </div>
        <div class="flex space-x-2">
          <a-button @click="previewResume">
            <template #icon><EyeOutlined /></template>
            预览
          </a-button>
          <a-button type="primary" @click="saveResume" :loading="saving">
            <template #icon><SaveOutlined /></template>
            保存
          </a-button>
        </div>
      </div>

      <!-- 编辑区域 -->
      <div class="flex flex-col lg:flex-row gap-6">
        <!-- 左侧导航 -->
        <div class="lg:w-64 bg-white dark:bg-gray-800 rounded-lg shadow p-4">
          <a-menu 
            v-model:selectedKeys="[activeTab]" 
            mode="inline"
            class="border-r-0"
          >
            <a-menu-item key="basic">
              <template #icon><UserOutlined /></template>
              基本信息
            </a-menu-item>
            <a-menu-item key="education">
              <template #icon><BookOutlined /></template>
              教育经历
            </a-menu-item>
            <a-menu-item key="work">
              <template #icon><BankOutlined /></template>
              工作经验
            </a-menu-item>
            <a-menu-item key="projects">
              <template #icon><ProjectOutlined /></template>
              项目经历
            </a-menu-item>
            <a-menu-item key="skills">
              <template #icon><ToolOutlined /></template>
              技能特长
            </a-menu-item>
            <a-menu-item key="certificates">
              <template #icon><TrophyOutlined /></template>
              证书奖项
            </a-menu-item>
            <a-menu-item key="template">
              <template #icon><LayoutOutlined /></template>
              模板选择
            </a-menu-item>
          </a-menu>
        </div>

        <!-- 右侧内容区 -->
        <div class="flex-1 bg-white dark:bg-gray-800 rounded-lg shadow p-6">
          <!-- 基本信息 -->
          <div v-show="activeTab === 'basic'">
            <h2 class="text-xl font-bold mb-4">基本信息</h2>
            <a-form layout="vertical">
              <a-row :gutter="16">
                <a-col :span="12">
                  <a-form-item label="姓名">
                    <a-input v-model:value="resume.basicInfo.name" placeholder="请输入姓名" />
                  </a-form-item>
                </a-col>
                <a-col :span="12">
                  <a-form-item label="职位">
                    <a-input v-model:value="resume.basicInfo.title" placeholder="期望职位" />
                  </a-form-item>
                </a-col>
              </a-row>

              <a-row :gutter="16">
                <a-col :span="12">
                  <a-form-item label="电子邮箱">
                    <a-input v-model:value="resume.basicInfo.contact.email" placeholder="电子邮箱" />
                  </a-form-item>
                </a-col>
                <a-col :span="12">
                  <a-form-item label="电话">
                    <a-input v-model:value="resume.basicInfo.contact.phone" placeholder="联系电话" />
                  </a-form-item>
                </a-col>
              </a-row>

              <a-row :gutter="16">
                <a-col :span="12">
                  <a-form-item label="地址">
                    <a-input v-model:value="resume.basicInfo.contact.address" placeholder="所在城市" />
                  </a-form-item>
                </a-col>
                <a-col :span="12">
                  <a-form-item label="个人网站">
                    <a-input v-model:value="resume.basicInfo.contact.website" placeholder="个人网站" />
                  </a-form-item>
                </a-col>
              </a-row>

              <a-row :gutter="16">
                <a-col :span="12">
                  <a-form-item label="GitHub">
                    <a-input v-model:value="resume.basicInfo.contact.github" placeholder="GitHub 主页" />
                  </a-form-item>
                </a-col>
                <a-col :span="12">
                  <a-form-item label="LinkedIn">
                    <a-input v-model:value="resume.basicInfo.contact.linkedin" placeholder="LinkedIn 主页" />
                  </a-form-item>
                </a-col>
              </a-row>

              <a-form-item label="个人简介">
                <a-textarea 
                  v-model:value="resume.basicInfo.objective" 
                  placeholder="简要介绍自己的背景、优势和求职目标" 
                  :rows="4" 
                />
              </a-form-item>
            </a-form>
          </div>

          <!-- 教育经历 -->
          <div v-show="activeTab === 'education'">
            <div class="flex justify-between items-center mb-4">
              <h2 class="text-xl font-bold">教育经历</h2>
              <a-button type="primary" @click="addEducation">
                <template #icon><PlusOutlined /></template>
                添加教育经历
              </a-button>
            </div>

            <div v-if="resume.education && resume.education.length > 0">
              <a-collapse>
                <a-collapse-panel 
                  v-for="(edu, index) in resume.education" 
                  :key="edu.id"
                  :header="edu.institution || `教育经历 ${index + 1}`"
                >
                  <a-form layout="vertical">
                    <a-row :gutter="16">
                      <a-col :span="12">
                        <a-form-item label="学校/机构名称">
                          <a-input v-model:value="edu.institution" placeholder="学校/机构名称" />
                        </a-form-item>
                      </a-col>
                      <a-col :span="12">
                        <a-form-item label="学位">
                          <a-input v-model:value="edu.degree" placeholder="学位" />
                        </a-form-item>
                      </a-col>
                    </a-row>

                    <a-row :gutter="16">
                      <a-col :span="12">
                        <a-form-item label="专业">
                          <a-input v-model:value="edu.major" placeholder="专业" />
                        </a-form-item>
                      </a-col>
                      <a-col :span="12">